--------------------------Package--------------------------
module ("base_proto" , package.seeall)
------------------------protocol func-----------------------
function get_data(args)
	cmds = {}
	for j,v in ipairs(args) do
		if type(v) == "string" then
			fp = io.open (v, "r")
			if io.type(fp) == nil then
				table.insert(cmds, v)
			else
				table.insert(cmds, fp:read ("*a"))
				io.close(fp)
			end
		elseif type(v) == "function" then
			table.insert(cmds, v())
		else
			print(string.format('get_data args error(%s)', type(v)))
		end
	end
	return table.concat(cmds)
end

function get_cmd_iter(cmd_seq, cmd_conf)
	local i = 0
	return function ()
		i = i + 1
		cmds = {}
		if(cmd_seq[i] == nil) then
			return nil
		end
		for j,v in ipairs(cmd_seq[i]) do		
			table.insert(cmds, cmd_conf[v][1][1](cmd_conf[v][1][2]))
		end
		return table.concat(cmds)
	end
end

function get_cmd(cmd)
	if type(cmd) == "string" then
		return cmd
	elseif type(cmd) == "function" then
		return cmd()
	else 
		print "error get_cmd fail"
		return nil
	end
end

local function split_cmd_line(cmd, line_split)
	cmd_list = {}
	len = string.len(cmd)
	i = 0
	n = 0
	m = 0
	while i < len do
		i,j = string.find(cmd, line_split, m)
		if(i ~= nil) then
			n = n + 1
			cmd_list[n] = string.sub(cmd, m, j)
			m = j + 1
		else
			break;
		end
	end 
	return cmd_list
end

local function draw_cmd(cmd, line_split, cmd_split)
	cmd = split_cmd_line(cmd, line_split)
	cmd_list = {}
	n = 0
	for j,v in ipairs(cmd) do
		i,m = string.find(v, cmd_split)
		n = n + 1
		if(i ~= nil) then
			cmd_list[n] = string.sub(v, 0, i - 1)
		else
			cmd_list[n] = v
		end
	end
	return cmd_list
end

function get_res(cmd, cmd_conf, line_split, cmd_split)
	cmd_list = draw_cmd(cmd, line_split, cmd_split)
	res_list = {}
	if cmd_list == nil or table.getn(cmd_list) == 0 then
		return nil
	else
		for j,v in ipairs(cmd_list) do
			res = cmd_conf[v][2]
			if type(res[1]) == "string" then
				table.insert(res_list, res[1])
			elseif type(res[1]) == "function" then
				table.insert(res_list, res[1](res[2]))
			else 
				print "error get_res fail"
			end
		end
		return table.concat(res_list)
	end
end